package com.lean.android.ad.duration

import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.lean.android.ad.duration.database.DurationDatabase
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

object DurationManager {

    private lateinit var appDurationFlow: Flow<Long>

    private lateinit var database: DurationDatabase


    fun init(app: Application) {
        database = DurationDatabase.createDatabase(app.applicationContext)
        //页面停留时间统计
//        app.registerActivityLifecycleCallbacks(PageDurationDetector(database))
        ProcessLifecycleOwner.get().lifecycle.addObserver(AppDurationDetector(database))
        appDurationFlow = database.getAppDurationDao().getTotalAppDuration()
    }

    fun getAppDurationFlow(): Flow<Long> {
        if (!::appDurationFlow.isInitialized) {
            throw RuntimeException("you must call DurationManager.init() first before use.")
        }
        return appDurationFlow
    }

    fun clearAppDuration() {
        if (!::database.isInitialized) return
        ProcessLifecycleOwner.get().lifecycleScope.launch {
            database.getAppDurationDao().deleteAll()
        }
    }
}